﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Com.Alipay;
using Model;

namespace SuuntoWebsite.Events._201205.Payment
{
    public partial class Callback : System.Web.UI.Page
    {
        protected static string sqlCon = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_Event"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            SortedDictionary<string, string> sPara = GetRequestPost();

            if (sPara.Count > 0)//判断是否有带返回参数
            {
                InsertLog(sPara);
                Notify aliNotify = new Notify();
                bool verifyResult = aliNotify.Verify(sPara, Request.Form["notify_id"], Request.Form["sign"],sqlCon);

                if (verifyResult)//验证成功
                {
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    //请在这里加上商户的业务逻辑程序代码

                    //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
                    //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
                    string trade_no = Request.Form["trade_no"];         //支付宝交易号
                    string order_no = Request.Form["out_trade_no"];     //获取订单号
                    string total_fee = Request.Form["price"];           //获取总金额
                    string subject = Request.Form["subject"];           //商品名称、订单名称
                    string body = Request.Form["body"];                 //商品描述、订单备注、描述
                    string buyer_email = Request.Form["buyer_email"];   //买家支付宝账号
                    string trade_status = Request.Form["trade_status"]; //交易状态

                    //实例化订单修改实体
                    ModelEvent.ModelSuunto_Order model = new ModelEvent.ModelSuunto_Order();
                    model.PKID = order_no;
                    model.State = trade_status;
                    model.UpdateTime = DateTime.Now;
                    //实例化结束

                    if (Request.Form["trade_status"] == "WAIT_BUYER_PAY")
                    {//该判断表示买家已在支付宝交易管理中产生了交易记录，但没有付款

                        //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                        //如果有做过处理，不执行商户的业务程序
                        model.State = "买家未付款";
                        bool flag = new Bll.EventForSuunto.BLLSuunto_Order().SuuntoOrderUpdate(sqlCon, model);
                       if (flag) Response.Write("success");  //请不要修改或删除
                       //Response.Write("success");
                    }
                    else if (Request.Form["trade_status"] == "WAIT_SELLER_SEND_GOODS")
                    {//该判断示买家已在支付宝交易管理中产生了交易记录且付款成功，但卖家没有发货

                        //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                        //如果有做过处理，不执行商户的业务程序

                        model.State = "买家以付款，等待卖家发货";
                        bool flag = new Bll.EventForSuunto.BLLSuunto_Order().SuuntoOrderUpdate(sqlCon, order_no, model.State, DateTime.Now);
                        if(flag) Response.Write("success");  //请不要修改或删除
                        //Response.Write("success");
                    }
                    else if (Request.Form["trade_status"] == "WAIT_BUYER_CONFIRM_GOODS")
                    {//该判断表示卖家已经发了货，但买家还没有做确认收货的操作

                        //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                        //如果有做过处理，不执行商户的业务程序

                        model.State = "卖家以发货，等待买家确认收货";
                        bool flag = new Bll.EventForSuunto.BLLSuunto_Order().SuuntoOrderUpdate(sqlCon, order_no, model.State, DateTime.Now);
                        if(flag) Response.Write("success");  //请不要修改或删除
                        //Response.Write("success");
                    }
                    else if (Request.Form["trade_status"] == "TRADE_FINISHED")
                    {//该判断表示买家已经确认收货，这笔交易完成

                        //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                        //如果有做过处理，不执行商户的业务程序

                        model.State = "买家确认收货，交易完成";
                        bool flag = new Bll.EventForSuunto.BLLSuunto_Order().SuuntoOrderUpdate(sqlCon, order_no, model.State, DateTime.Now);

                        if (flag) Response.Write("success");  //请不要修改或删除
                        //Response.Write("success");
                    }
                    else
                    {
                        Response.Write("success");  //其他状态判断。
                    }

                    //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
                else//验证失败
                {
                    Response.Write("fail");
                }
            }
            else
            {
                Response.Write("无通知参数");
            }
        }
        /// <summary>
        /// 获取支付宝POST过来通知消息，并以“参数名=参数值”的形式组成数组
        /// </summary>
        /// <returns>request回来的信息组成的数组</returns>
        public SortedDictionary<string, string> GetRequestPost()
        {
            int i = 0;
            SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
            NameValueCollection coll;
            //Load Form variables into NameValueCollection variable.
            coll = Request.Form;

            // Get names of all forms into a string array.
            String[] requestItem = coll.AllKeys;

            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.Form[requestItem[i]]);
            }

            return sArray;
        }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="par">支付宝返回实体</param>
        public void InsertLog(SortedDictionary<string,string> par)
        {
            ModelEvent.ModelSuunto_Paylog model = new ModelEvent.ModelSuunto_Paylog();
            try
            {
                if (par.Count == 31)
                {
                    model.Body = par["body"];
                    model.buyer_email = par["buyer_email"];
                    model.buyer_id = par["buyer_id"];
                    model.discount = par["discount"];
                    model.gmt_create = par["gmt_create"];
                    model.gmt_logistics_modify = par["gmt_logistics_modify"];
                    model.gmt_payment = par["gmt_payment"];
                    model.is_total_fee_adjust = par["is_total_fee_adjust"];
                    model.logistics_fee = par["logistics_fee"];
                    model.logistics_payment = par["logistics_payment"];
                    model.logistics_type = par["logistics_type"];
                    model.notify_id = par["notify_id"];
                    model.notify_time = par["notify_time"];
                    model.notify_type = par["notify_type"];
                    model.out_trade_no = par["out_trade_no"];
                    model.payment_type = par["payment_type"];
                    model.price = par["price"];
                    model.quantity = par["quantity"];
                    model.receive_address = par["receive_address"];
                    model.receive_mobile = par["receive_mobile"];
                    model.receive_name = par["receive_name"];
                    model.receive_zip = par["receive_zip"];
                    model.seller_email = par["seller_email"];
                    model.seller_id = par["seller_id"];
                    model.sign = par["sign"];
                    model.sign_type = par["sign_type"];
                    model.subject = par["subject"];
                    model.total_fee = par["total_fee"];
                    model.trade_no = par["trade_no"];
                    model.trade_status = par["trade_status"];
                    model.use_coupon = par["use_coupon"];
                    model.request_page = this.Page.GetType().Name;
                }
                else
                {
                    model.Body = par["body"];
                    model.buyer_email = par["buyer_email"];
                    model.buyer_id = par["buyer_id"];
                    model.discount = par["discount"];
                    model.gmt_create = par["gmt_create"];
                    model.is_total_fee_adjust = par["is_total_fee_adjust"];
                    model.notify_id = par["notify_id"];
                    model.notify_time = par["notify_time"];
                    model.notify_type = par["notify_type"];
                    model.out_trade_no = par["out_trade_no"];
                    model.payment_type = par["payment_type"];
                    model.price = par["price"];
                    model.quantity = par["quantity"];
                    model.seller_email = par["seller_email"];
                    model.seller_id = par["seller_id"];
                    model.sign = par["sign"];
                    model.sign_type = par["sign_type"];
                    model.subject = par["subject"];
                    model.total_fee = par["total_fee"];
                    model.trade_no = par["trade_no"];
                    model.trade_status = par["trade_status"];
                    model.use_coupon = par["use_coupon"];
                    model.request_page = this.Page.GetType().Name;
                }
                System.Text.StringBuilder parStr = new System.Text.StringBuilder();
                foreach (KeyValuePair<string, string> item in par)
                {
                    parStr.Append(item.Key + "=" + item.Value + "&");
                }
                parStr.Append("parCount=" + par.Count);
                model.Description = parStr.ToString();
                new Bll.EventForSuunto.BLLSuunto_Paylog().SuuntoPaylogInsert(sqlCon, model);
            }
            catch (Exception ex)
            {
                System.Text.StringBuilder parStr = new System.Text.StringBuilder();
                foreach (KeyValuePair<string, string> item in par)
                {
                    parStr.Append(item.Key + "=" + item.Value + "&");
                }
                parStr.Append("parCount=" + par.Count);
                model.Description = parStr.ToString();
                new Bll.EventForSuunto.BLLSuunto_Paylog().SuuntoPaylogInsert(sqlCon, model);
            }
        }
    }
}
